package edu.gyc.stu.filter;

import java.io.IOException;
import java.util.logging.Logger;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import edu.gyc.stu.model.User;

/**
 * 对指定路径下的请求进行session的失效验证，如失效则跳转到登录页面
 * @author Administrator
 *
 */
public class ReqFilter implements Filter{

    private static Logger logger = Logger.getLogger("RegFilter");


    @Override
    public void destroy() {
        // TODO Auto-generated method stub

    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;

        //取到url路径的最后一个路径名
        String uri = request.getRequestURI();
        uri = uri.substring(uri.lastIndexOf("/")+1);

        if("".equals(uri) || "reg.jsp".equals(uri) || "login".equals(uri) || "reg".equals(uri)
                || "login.jsp".equals(uri) ||uri.endsWith("png") || uri.endsWith("jpg")||
                uri.endsWith("js")|| uri.endsWith("css")) {
            //所有人都能请求到的URI，放行
            chain.doFilter(request, response);
        } else {
            //下面是判断是否有session，也就是用户是否已登录状态；
            HttpSession session = request.getSession();
            User user = (User) session.getAttribute("user");
            if(user == null) {
                //打印一下访问被拒绝的文件

                logger.info("URI:" + uri + ">>>>访问被拒绝！");
                String path=request.getContextPath();
                response.sendRedirect(path+"/login.jsp");
            } else {
                chain.doFilter(request, response);
            }
        }

    }

    @Override
    public void init(FilterConfig arg0) throws ServletException {
        // TODO Auto-generated method stub

    }

}
